package com.cedifie.lendapp.ui.steps.fm

import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import com.cedifie.lendapp.R
import com.cedifie.lendapp.databinding.FmStepOcrIdcardBinding
import com.cedifie.lendapp.http.ApiService
import com.cedifie.lendapp.http.ApiService.addCommonParams
import com.cedifie.lendapp.http.HttpHelper
import com.cedifie.lendapp.ui.steps.act.CedCameraOcrAct
import com.cedifie.lendapp.ui.steps.act.CedOcrUploadAct
import com.cedifie.lendapp.ui.steps.act.CedStepAct
import com.cedifie.lendapp.utils.dialog.PhotoDialog
import com.cedifie.lendapp.utils.event.CedEventData
import com.cedifie.lendapp.utils.event.CedEventManager
import com.cedifie.lendapp.utils.event.CedEventType
import com.cedifie.lendapp.utils.imagecovert.ImageConvert
import com.lib.base.base.BaseFragment
import com.lib.base.utils.ImageUtil
import com.lib.base.utils.log.LogHelper
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONObject

/**
 * Cedifie
 * @Author wwdeng
 * @CreateTime: 2024/6/20 17:59
 * @Annotation：Ocr - 身份证
 */
class CedOcrIDCardFm(): BaseFragment() {
    private var _binding: FmStepOcrIdcardBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "binding is null"
    )
    //证件照 || 选举卡 || 驾照  IDCARD  ELECTIONCARD DRIVING
    private var ocrType = "IDCARD"

    private var isFront = false//是否是正面
    //正面照
    private var imgFrontUrl = ""
    //背面照
    private var imgBackUrl = ""
    //图片选择
    private lateinit var pickMedia: ActivityResultLauncher<PickVisualMediaRequest>

    constructor(ocrType: String): this(){
        this.ocrType = ocrType
    }

    override fun getCedRootView(inflater: LayoutInflater): View {
        _binding = FmStepOcrIdcardBinding.inflate(inflater)
        return binding.root
    }

    override fun initCedView() {
        rootViewBinding.containerLayout.setBackgroundColor(Color.parseColor("#00000000"))

        EventBus.getDefault().register(this)
        // 1-注册图库组件
        pickMedia = registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
            if (uri != null) {
                // 图片处理
                ImageConvert.covert(context = requireContext(), uri = uri) { localPath, bitmap ->
                    if (localPath != null){
                        launch(Dispatchers.Main){
                            delay(200)
                            CedOcrUploadAct.start(requireContext(),ocrType,localPath)
                        }
                    }
                }
            } else {
                LogHelper.e("No media selected")
            }
        }
        when(ocrType){//IDCARD  ELECTIONCARD DRIVING
            "IDCARD" -> {
                _binding?.textFront?.text = getString(R.string.process_ocr_idcard_front)
                _binding?.textBack?.text = getString(R.string.process_ocr_idcard_back)
            }
            "DRIVING" -> {
                _binding?.textFront?.text = getString(R.string.process_ocr_drving_license_front)
                _binding?.textBack?.text = getString(R.string.process_ocr_drving_license_back)
            }
            else -> {
                _binding?.textFront?.text = getString(R.string.process_ocr_election_card_front)
                _binding?.textBack?.text = getString(R.string.process_ocr_election_card_back)
            }
        }
    }

    override fun initCedListener() {
        //身份证正面
        _binding?.frontLayout?.setOnClickListener {
            isFront = true
            showPhotoDialog("$ocrType Front")
        }

        //身份证反面
        _binding?.backLayout?.setOnClickListener {
            isFront = false
            showPhotoDialog("$ocrType Back")
        }

        //下一步
        _binding?.btnNext?.setOnClickListener {
            if (imgFrontUrl.isEmpty() || imgBackUrl.isEmpty()){
                showCedToast(getString(R.string.tips_submit_error))
                return@setOnClickListener
            }
            when(ocrType){//IDCARD  ELECTIONCARD DRIVING
                "IDCARD" -> {
                    HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_STEP_OCR_IDCARD_NEXT,"")
                }
                "DRIVING" -> {
                    HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_STEP_OCR_DRIVERLICENSE_NEXT,"")
                }
                else -> {
                    HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_STEP_OCR_ELECTIONCARD_NEXT,"")
                }
            }
            //立即上报
            CedEventManager.getInstance().updateCedEventsNow()

            val params = JSONObject().addCommonParams().apply {
                put("path",ApiService.API_PATH.CED_API_OCR_INFO_PATH)
                put("cardType",ocrType)//证件类型（PASSPORT、IDCARD、DRIVING、FACE）
                put("cardImgUrl",imgFrontUrl)//证件图片正面
                put("cardBackImgUrl",imgBackUrl)//证件图片反面
            }
            if (ocrType == "ELECTIONCARD"){//选举卡当作 IDCARD 类型上传
                params.put("cardType","IDCARD")//证件类型（PASSPORT、IDCARD、DRIVING、FACE）
            }
            val act = context as CedStepAct
            act.onSubmitProcessAction(params)
        }
    }

    override fun initCedData() {
        when(ocrType){//IDCARD  ELECTIONCARD DRIVING
            "IDCARD" -> {
                HttpHelper.addCedEventAction(String.format(CedEventType.PAGE.CED_PAGE_STEP_OCR_XX_START,"IdCard"),"")
            }
            "DRIVING" -> {
                HttpHelper.addCedEventAction(String.format(CedEventType.PAGE.CED_PAGE_STEP_OCR_XX_START,"DriverLicense"),"")
            }
            else -> {
                HttpHelper.addCedEventAction(String.format(CedEventType.PAGE.CED_PAGE_STEP_OCR_XX_START,"ElectionCard"),"")
            }
        }
    }

    /**
     * 收到使用照片通知
     */
    @Subscribe(threadMode = ThreadMode.POSTING)
    fun onCedUserPhotoReceive(data: CedEventData){
        if (data.eventType == CedEventData.TYPE.CED_USE_PHOTO){
            //图片网络地址
            val imgUrl = data.eventData.optString("imgUrl")
            //图片本地地址
            val imgPath = data.eventData.optString("imgPath")
            LogHelper.e(">>>>>>>>>>>>>>>>>>>>>>>>>>>>user photo imgUrl ： $imgUrl")
            _binding?.let {
                if (isFront){
                    imgFrontUrl = imgUrl
                    ImageUtil.instance?.loadImageUrl(requireContext(),it.imgFront,imgPath)
                } else {
                    imgBackUrl = imgUrl
                    ImageUtil.instance?.loadImageUrl(requireContext(),it.imgBack,imgPath)
                }
            }
        }
    }

    /**
     * 相机、相册选择
     */
    private fun showPhotoDialog(eventRemark: String){
        val photoDialog = PhotoDialog(context,eventRemark,object : PhotoDialog.IDialogCallback{
            override fun openCamera() {
                HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_CAMERA,eventRemark)
                onOpenCamera()
            }
            override fun openAlbum() {
                HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_ALBUM,eventRemark)
                onOpenAlbum()
            }
        })
        photoDialog.show()
    }

    /**
     * 打开相机
     */
    private fun onOpenCamera(){
        CedCameraOcrAct.start(requireContext(),ocrType)
    }

    /**
     * 打开相册
     */
    private fun onOpenAlbum(){
        pickMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
        when(ocrType){//IDCARD  ELECTIONCARD DRIVING
            "IDCARD" -> {
                HttpHelper.addCedEventAction(String.format(CedEventType.PAGE.CED_PAGE_STEP_OCR_XX_END,"IdCard"),"")
            }
            "DRIVING" -> {
                HttpHelper.addCedEventAction(String.format(CedEventType.PAGE.CED_PAGE_STEP_OCR_XX_END,"DriverLicense"),"")
            }
            else -> {
                HttpHelper.addCedEventAction(String.format(CedEventType.PAGE.CED_PAGE_STEP_OCR_XX_END,"ElectionCard"),"")
            }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}